package cn.jaye.fabric.controller.rest;

import cn.jaye.fabric.application.AuthApplicationService;
import cn.jaye.fabric.application.command.LoginCommand;
import cn.jaye.fabric.application.command.RegistCommand;
import cn.jaye.fabric.common.constant.ExceptionEnum;
import cn.jaye.fabric.common.model.SystemSession;
import cn.jaye.fabric.common.util.ResultUtil;
import cn.jaye.fabric.domain.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Jaye
 * @create 2018-06-05 15:56
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private AuthApplicationService authApplicationService;

    @PostMapping("register")
    public String register(RegistCommand registCommand) throws InterruptedException {
        if (null != registCommand.getPassword() && null != registCommand.getVoucherCode()) {
            if (registCommand.getPassword().equals(registCommand.getRepeatPassword())) {
                return ResultUtil.success(authApplicationService.register(registCommand));
            }
        }
        return ResultUtil.error(ExceptionEnum.USER_REGISTER_PASSWORD_EEROR);
    }

    @PostMapping("login")
    public String login(HttpServletRequest request, LoginCommand loginCommand) {
        if (authApplicationService.login(loginCommand)) {
            request.getSession().setAttribute("username", loginCommand.getUsername());
            return ResultUtil.success();
        }
        return ResultUtil.error(ExceptionEnum.USER_LOGIN_FAILED);
    }

    @PostMapping("loginout")
    public String loginout(HttpServletRequest request) {
        request.getSession().setAttribute("username", null);
        return ResultUtil.success();
    }
}
